import { Debounce } from "@/utils/validate.js";
import Cache from "../utils/cache";
import store from "../store";
export const toLogin = Debounce(_toLogin, 800);
import {
  LOGIN_STATUS,
  USER_INFO,
  EXPIRES_TIME,
  STATE_R_KEY,
  BACK_URL,
} from "./../config/cache";
function prePage() {
  let pages = getCurrentPages();
  let prePage = pages[pages.length - 1];
  return prePage.route;
}
export function _toLogin(push, pathLogin) {
  store.commit("LOGOUT");
  let path = prePage();
  let login_back_url = Cache.get(BACK_URL);

  if (!pathLogin) {
    pathLogin = "/page/users/login/index";
    Cache.set("login_back_url", path);
  }

  if (
    ["pages/users/index", "/pages/users/index"].indexOf(login_back_url) == -1
  ) {
    // #ifdef MP
    uni.navigateTo({
      url: "/pages/users/index",
    });
    // #endif
  }
}
export function checkLogin() {
  let token = Cache.get(LOGIN_STATUS);
  let expiresTime =
    uni.getStorageSync(`tokenStr_${process.env.ENV_TYPE}_3H5`) || "";
  let newTime = Math.round(new Date() / 1000);
  if (expiresTime < newTime || !token) {
    Cache.clear(LOGIN_STATUS);
    Cache.clear(EXPIRES_TIME);
    Cache.clear(USER_INFO);
    return false;
  } else {
    store.commit("UPDATE_LOGIN", token);
    let userInfo = Cache.get(USER_INFO, true);
    if (userInfo) {
      store.commit("UPDATE_USERINFO", userInfo);
    }
    return true;
  }
}
